In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
Visualize the German Traffic Signs Dataset. This is open ended, some suggestions include: plotting traffic signs images, plotting the count of each sign, etc. Be creative!
The pickled data is a dictionary with 4 key/value pairs:
print('Loading data...')
# Load pickled data
import pickle
training_file = './train.p'
testing_file = './test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
train_features, train_labels = train['features'], train['labels']
test_features, test_labels = test['features'], test['labels']
print('Done loading data')
### To start off let's do a basic data summary.
n_train = len(train_features)
n_test = len(test_features)
image_shape = "{}x{}".format(len(train_features[0]), len(train_features[0][0]))
n_classes = max(train_labels) + 1
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
train_features = np.array(train['features'])
train_labels = np.array(train['labels'])
inputs_per_class = np.bincount(train_labels)
max_inputs = np.max(inputs_per_class)
mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)
ax.set_ylabel('Inputs')
ax.set_xlabel('Class')
ax.set_title('Number of inputs per class')
ax.bar(range(len(inputs_per_class)), inputs_per_class, 1/3, color='blue', label='Inputs per class')
plt.show()
for i in range(n_classes):
for j in range(len(train_labels)):
if (i == train_labels[j]):
print('Class: ', i)
plt.imshow(train_features[j])
plt.show()
break
print('Data visualisation complete')
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
print('Preprocessing data...')
# Generate additional data for underrepresented classes
print('Generating additional data...')
angles = [-5, 5, -10, 10, -15, 15, -20, 20]
for i in range(len(inputs_per_class)):
input_ratio = min(int(max_inputs / inputs_per_class[i]) - 1, len(angles) - 1)
if input_ratio <= 1:
continue
new_features = []
new_labels = []
mask = np.where(train_labels == i)
for j in range(input_ratio):
for feature in train_features[mask]:
new_features.append(scipy.ndimage.rotate(feature, angles[j], reshape=False))
new_labels.append(i)
train_features = np.append(train_features, new_features, axis=0)
train_labels = np.append(train_labels, new_labels, axis=0)
# Normalize features
print('Normalizing features...')
train_features = train_features / 255. * 0.8 + 0.1
# Get randomized datasets for training and validation
print('Randomizing datasets...')
from sklearn.model_selection import train_test_split
train_features, valid_features, train_labels, valid_labels = train_test_split(
train_features,
train_labels,
test_size=0.2,
random_state=832289
)
print('Data preprocessed')
inputs_per_class = np.bincount(train_labels)
mpl_fig = plt.figure()
ax = mpl_fig.add_subplot(111)
ax.set_ylabel('Inputs')
ax.set_xlabel('Class')
ax.set_title('Number of inputs per class')
ax.bar(range(len(inputs_per_class)), inputs_per_class, 1/3, color='blue', label='Inputs per class')
plt.show()
print('Creating network architecture...')
import tensorflow as tf
# Input dimensions
image_width = len(train_features[0][0])
image_height = len(train_features[0])
color_channels = len(train_features[0][0][0])
# Convolutional layer patch and output size
filter_width = 3
filter_height = 3
conv_k_output = 128
# Dimension parameters for each fully connected layer
fc_params = [
image_width * image_height * conv_k_output,
1024,
1024,
n_classes
]
# Build weights and biases
conv2d_weight = None
conv2d_bias = None
fc_weights = []
fc_biases = []
with tf.variable_scope('BONHOMME', reuse=False):
conv2d_weight = tf.get_variable("conv2w", shape=[filter_width, filter_height, color_channels, conv_k_output], initializer=tf.contrib.layers.xavier_initializer())
conv2d_bias = tf.get_variable("conv2b", shape=[conv_k_output], initializer=tf.contrib.layers.xavier_initializer())
for i in range(len(fc_params) - 1):
fc_weights.append(tf.get_variable('fc_weight' + str(i), shape=[fc_params[i], fc_params[i + 1]], initializer=tf.contrib.layers.xavier_initializer()))
fc_biases.append(tf.get_variable('fc_bias' + str(i), shape=[fc_params[i + 1]], initializer=tf.contrib.layers.xavier_initializer()))
# One-hot encoded training and validation labels
oh_train_labels = tf.one_hot(train_labels, n_classes).eval(session=tf.Session())
oh_valid_labels = tf.one_hot(valid_labels, n_classes).eval(session=tf.Session())
# Input placeholders
input_ph = tf.placeholder(tf.float32, shape=[None, image_width, image_height, color_channels])
labels_ph = tf.placeholder(tf.float32)
# Convolutional layer
network = tf.nn.conv2d(input_ph, conv2d_weight, strides=[1, 1, 1, 1], padding='SAME')
network = tf.nn.bias_add(network, conv2d_bias)
network = tf.nn.relu(network)
# Fully connected layers
for i in range(len(fc_weights)):
network = tf.matmul(tf.contrib.layers.flatten(network), fc_weights[i]) + fc_biases[i]
if i < len(fc_weights) - 1: # No relu after last FC layer
network = tf.nn.relu(network)
# Loss computation
prediction = tf.nn.softmax(network)
cross_entropy = -tf.reduce_sum(labels_ph * tf.log(prediction + 1e-6), reduction_indices=1)
loss = tf.reduce_mean(cross_entropy)
# Accuracy computation
is_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels_ph, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))
print('Network architecture created')
test_features = np.array(test_features) / 255 * 0.8 + 0.1
oh_test_labels = tf.one_hot(test_labels, n_classes).eval(session=tf.Session())
print('Test label one hot encoded')
batch_size = 150
def run_batch(session, network, features, labels):
batch_count = int(len(features) / batch_size)
accuracy = 0
for i in range(batch_count):
batch_start = i * batch_size
accuracy += session.run(
network,
feed_dict={
input_ph: features[batch_start:batch_start + batch_size],
labels_ph: labels[batch_start:batch_start + batch_size]
}
)
return accuracy / batch_count
print('Run batch function created')
from tqdm import tqdm
training_epochs = 100
optimizer = tf.train.AdamOptimizer().minimize(loss)
log_batch_step = 100
batches = []
loss_batch = []
train_acc_batch = []
valid_acc_batch = []
validation_accuracy = 0.0
init = tf.global_variables_initializer()
session = tf.Session(config=tf.ConfigProto(log_device_placement=True))
session.run(init)
batch_count = int(len(train_features) / batch_size)
for epoch in range(training_epochs):
batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch + 1, training_epochs), unit='batches')
# The training cycle
for batch_i in batches_pbar:
batch_start = batch_i * batch_size
batch_features = train_features[batch_start:batch_start + batch_size]
batch_labels = oh_train_labels[batch_start:batch_start + batch_size]
_, l = session.run(
[optimizer, loss],
feed_dict={input_ph: batch_features, labels_ph: batch_labels})
if not batch_i % log_batch_step:
training_accuracy = session.run(
accuracy,
feed_dict={input_ph: batch_features, labels_ph: batch_labels}
)
idx = np.random.randint(len(valid_features), size=int(batch_size * .2))
validation_accuracy = session.run(
accuracy,
feed_dict={input_ph: valid_features[idx,:], labels_ph: oh_valid_labels[idx,:]}
)
# Log batches
previous_batch = batches[-1] if batches else 0
batches.append(log_batch_step + previous_batch)
loss_batch.append(l)
train_acc_batch.append(training_accuracy)
valid_acc_batch.append(validation_accuracy)
validation_accuracy = run_batch(session, accuracy, valid_features, oh_valid_labels)
test_accuracy = run_batch(session, accuracy, test_features, oh_test_labels)
print('Final validation accuracy: ', validation_accuracy)
print('Final test accuracy: ', test_accuracy)
loss_plot = plt.subplot(211)
loss_plot.set_title('Loss')
loss_plot.plot(batches, loss_batch, 'g')
loss_plot.set_xlim([batches[0], batches[-1]])
acc_plot = plt.subplot(212)
acc_plot.set_title('Accuracy')
acc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')
acc_plot.plot(batches, valid_acc_batch, 'b', label='Validation Accuracy')
acc_plot.set_ylim([0, 1.0])
acc_plot.set_xlim([batches[0], batches[-1]])
acc_plot.legend(loc=4)
plt.tight_layout()
plt.show()
Describe the techniques used to preprocess the data.
Answer:
"""
I noted that some classes were very underrepresented in the training data, some by a 1:9 ratio compared to some others
So for these classes, I generated additional data by rotating the pictures by incremental small angles
until I had a roughly similar amount of inputs for each class.
I then normalized the values between 0.1 and 0.9
Finally, as the input was sorted by class, I randomized it to avoid overfitting.
"""
test_batch_size = 250
y_pred_cls = tf.argmax(prediction, dimension=1)
test_cls = np.argmax(oh_test_labels, axis=1)
from pylab import rcParams
from sklearn.metrics import confusion_matrix
img_shape = (32, 32, 3)
def plot_images(images, cls_true, cls_pred=None):
assert len(images) == len(cls_true) == 9
# Create figure with 3x3 sub-plots.
fig, axes = plt.subplots(3, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.3)
for i, ax in enumerate(axes.flat):
# Plot image.
ax.imshow(images[i].reshape(img_shape), cmap='binary')
# Show true and predicted classes.
if cls_pred is None:
xlabel = "True: {0}".format(np.argmax(cls_true[i]))
else:
xlabel = "True: {0}, Pred: {1}".format(np.argmax(cls_true[i]), np.argmax(cls_pred[i]))
# Show the classes as the label on the x-axis.
ax.set_xlabel(xlabel)
# Remove ticks from the plot.
ax.set_xticks([])
ax.set_yticks([])
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
def plot_confusion_matrix(cls_pred):
# This is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# Get the confusion matrix using sklearn.
cm = confusion_matrix(y_true=test_cls,
y_pred=cls_pred)
plt.figure(figsize=(40,40))
rcParams['figure.figsize'] = 13, 13
# Plot the confusion matrix as an image.
plt.matshow(cm)
# Make various adjustments to the plot.
plt.colorbar()
tick_marks = np.arange(n_classes)
plt.xticks(tick_marks, range(n_classes))
plt.yticks(tick_marks, range(n_classes))
plt.xlabel('Predicted')
plt.ylabel('True')
# Ensure the plot is shown correctly with multiple plots
# in a single Notebook cell.
plt.show()
def plot_example_errors(cls_pred, correct):
# This function is called from print_test_accuracy() below.
# cls_pred is an array of the predicted class-number for
# all images in the test-set.
# correct is a boolean array whether the predicted class
# is equal to the true class for each image in the test-set.
# Negate the boolean array.
incorrect = (correct == False)
# Get the images from the test-set that have been
# incorrectly classified.
images = test_features[incorrect]
# Get the predicted classes for those images.
cls_pred = cls_pred[incorrect]
# Get the true classes for those images.
cls_true = test_cls[incorrect]
# Plot the first 9 images.
plot_images(images=images[0:9],
cls_true=cls_true[0:9],
cls_pred=cls_pred[0:9])
def print_test_accuracy(show_example_errors=False,
show_confusion_matrix=False):
# Number of images in the test-set.
num_test = len(test_features)
# Allocate an array for the predicted classes which
# will be calculated in batches and filled into this array.
cls_pred = np.zeros(shape=num_test, dtype=np.int)
# Now calculate the predicted classes for the batches.
# We will just iterate through all the batches.
# There might be a more clever and Pythonic way of doing this.
# The starting index for the next batch is denoted i.
i = 0
while i < num_test:
# The ending index for the next batch is denoted j.
j = min(i + test_batch_size, num_test)
batch_features = test_features[i:j]
batch_labels = oh_test_labels[i:j]
# Create a feed-dict with these images and labels.
feed_dict={input_ph: batch_features, labels_ph: batch_labels}
# Calculate the predicted class using TensorFlow.
cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict)
# Set the start-index for the next batch to the
# end-index of the current batch.
i = j
# Create a boolean array whether each image is correctly classified.
correct = (test_cls == cls_pred)
# Calculate the number of correctly classified images.
# When summing a boolean array, False means 0 and True means 1.
correct_sum = correct.sum()
# Classification accuracy is the number of correctly classified
# images divided by the total number of images in the test-set.
acc = float(correct_sum) / num_test
# Print the accuracy.
msg = "Accuracy on Test-Set: {0:.1%} ({1} / {2})"
print(msg.format(acc, correct_sum, num_test))
# Plot some examples of mis-classifications, if desired.
if show_example_errors:
print("Example errors:")
plot_example_errors(cls_pred=cls_pred, correct=correct)
# Plot the confusion matrix, if desired.
if show_confusion_matrix:
print("Confusion Matrix:")
plot_confusion_matrix(cls_pred=cls_pred)
print_test_accuracy(show_example_errors=False, show_confusion_matrix=True)
Describe how you set up the training, validation and testing data for your model. If you generated additional data, why?
Answer:
"""
I took 20% of the training data as validation data, which seemed enough to not overfit the data.
I didn't use the testing data until I got satisfying results with the network.
"""
What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.
Answer:
"""
First layer is a CNN with a patch size of 3*3, a stride of 1, SAME padding and a depth of 64
Second and third layers are fully connected layers with a width of 512
The final layer is a fully connected layer with a width of 43 (the amount of classes)
"""
How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)
Answer:
"""
I used the Adam optimizer with its default parameters as it is currently regarded as the most efficient.
I used a batch size of 250 and 30 training epochs.
"""
What approach did you take in coming up with a solution to this problem?
Answer:
"""
I tried adding more convolution networks but they didn't improve the results and increased the computation time by a lot.
It didn't feel that necessary to add them as there is a low statistical invariance between the pictures we work on.
Most of them are already centered and cropped around the sign.
I used a medium sized network as the signs are overall pretty simple in shape and color.
I used wide fully connected layers as there are some variations in the sign's shapes, colors and overall appearance.
I didn't use more than 30 epochs as the accuracy wasn't improving after that.
I also wanted to keep the network light so training it wouldn't take too much time on AWS and the results are satisfying as is.
"""
Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg
imgs = ['20.png', '80.png', 'exclamation.png', 'hochwasser.png', 'priority.png']
new_input = []
for imgname in imgs:
image = mpimg.imread('images/' + imgname)
new_input.append(image)
plt.imshow(image)
plt.show()
Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It would be helpful to plot the images in the notebook.
Answer:
### Run the predictions here.
### Feel free to use as many code cells as needed.
new_predictions = session.run(prediction, feed_dict={input_ph: new_input})
Is your model able to perform equally well on captured pictures or a live camera stream when compared to testing on the dataset?
Answer:
### Visualize the softmax probabilities here.
### Feel free to use as many code cells as needed.
print(new_predictions)
Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)
Answer:
print(session.run(tf.nn.top_k(prediction, 2), feed_dict={input_ph: new_input}))
"""
The model is pretty certain of all of its results except for one where it's only at 88% certainty.
When the model is wrong, the correct answer does not appear in the top 2. Prediction certainty after class 2 are meaningless so we don't analyze them.
"""
If necessary, provide documentation for how an interface was built for your model to load and classify newly-acquired images.
Answer:
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.